class Indxe {
    constructor() {
        this.ul = document.querySelector('.page-list')
        this.span = document.querySelector('#sidebar>.head>.span')
       $.get('../data/list.json').then((res)=>{
         this.datalist = res
       })
        this.init()
    }
    init() {
        this.add()
        this.count()
    }
    add(){
      this.ul.addEventListener('click',(e)=>{
        let target=e.target ||e.srcElement
        if(target.nodeName=='BUTTON'){
          let id=target.dataset.id
          let goods=this.datalist.find(item=>{return item.id==id})
          let list=JSON.parse(localStorage.getItem('cart'))||[]
          if(!list.length){
            list.push(goods)
            goods.cart_Num=1
          }else{
            let res=list.some(item=>{return item.id==id})
             if(res){
             let index=list.findIndex(item=>{return item.id==id})
              list[index].cart_Num++
             }else{
              list.push(goods)
              goods.cart_Num=1
             }
          }
         localStorage.setItem('cart',JSON.stringify(list))
         this.count()
        }
      },false)
    }
      count(){
        let list = JSON.parse(localStorage.getItem("cart")) || []
        let count = 0
        list.forEach((item)=>{
            count += item.cart_Num
        })
        this.span.innerHTML = count
    }  
  }
new Indxe()
